<template>
  <div class="add-site-container">
    <el-form :model="form" :rules="rules" ref="addSiteForm" label-width="100px">
      <!-- 表单项 -->
      <el-form-item label="站点名称" prop="siteName">
        <el-input v-model="form.siteName"></el-input>
      </el-form-item>
      <el-form-item label="站点地址" prop="siteAddress">
        <el-input v-model="form.siteAddress" @input="searchLocation"></el-input>
      </el-form-item>
      <el-form-item label="经度" prop="longitude">
        <el-input v-model="form.longitude" readonly></el-input>
      </el-form-item>
      <el-form-item label="纬度" prop="latitude">
        <el-input v-model="form.latitude" readonly></el-input>
      </el-form-item>
      <el-form-item label="站点联系人电话" prop="siteUserPhone">
        <el-input v-model="form.siteUserPhone"></el-input>
      </el-form-item>
      <el-form-item label="站点联系人姓名" prop="siteUserName">
        <el-input v-model="form.siteUserName"></el-input>
      </el-form-item>
      <el-form-item label="站点简介" prop="siteDesc">
        <el-input type="textarea" v-model="form.siteDesc"></el-input>
      </el-form-item>
      <el-button type="primary" @click="openMap">选择位置</el-button>
      <el-button type="success" @click="submitForm">提交</el-button>
    </el-form>

    <!-- 高德地图弹窗 -->
    <el-dialog title="选择位置" :visible.sync="mapVisible" width="80%">
      <el-autocomplete
        v-model="searchQuery"
        :fetch-suggestions="querySearchAsync"
        placeholder="请输入地点名称"
        @select="handleSelect"
        style="margin-bottom: 10px;"
      ></el-autocomplete>
      <div id="container" style="width:100%;height:500px;"></div>
    </el-dialog>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';

export default {
  data() {
    return {
      form: {
        siteName: '',
        siteAddress: '',
        longitude: null,
        latitude: null,
        siteUserPhone: '',
        siteUserName: '',
        siteDesc: ''
      },
      rules: {}, // 根据实际需求设置校验规则
      mapVisible: false,
      map: null,
      searchQuery: '', // 搜索地点的查询字符串
      placeSearch: null,
      isMapReady: false, // 新增标志位，用于标记地图和PlaceSearch是否已准备好
      suggestions: []
    };
  },
  mounted() {
    // 设置安全密钥
    window._AMapSecurityConfig = {
      securityJsCode: '3242f3455132c5fd8bbd976165cf3edd'
    };

    AMapLoader.load({
      key: "96b8191f938c9fee3541bd080df37ac1", 
      version: "2.0",
      plugins: ['AMap.ToolBar', 'AMap.PlaceSearch'] // 确保包含PlaceSearch插件
    }).then((AMap) => {
      this.AMap = AMap;
      console.log('高德地图API加载成功');
    }).catch(e => {
      console.error('地图加载失败:', e);
    });
  },
  methods: {
    searchLocation() {
      // 如果不需要处理输入事件，可以留空
    },
    openMap() {
      this.mapVisible = true;
      this.$nextTick(() => {
        if (!this.map && this.AMap) {
          const AMap = this.AMap;

          // 定义一个函数来初始化地图
          const initMap = (center = [116.397428, 39.90923]) => { // 默认使用北京坐标
            this.map = new AMap.Map('container', {zoom: 13, center: center});
            var toolbar = new AMap.ToolBar();
            this.map.addControl(toolbar); // 确保地图已初始化

            // 使用AMap.plugin方法加载PlaceSearch插件，并创建PlaceSearch实例
            AMap.plugin('AMap.PlaceSearch', () => {
              this.placeSearch = new AMap.PlaceSearch({map: this.map});
              this.isMapReady = true; // 设置地图和PlaceSearch已准备好
            });

            this.map.on('click', (e) => {
              this.form.longitude = e.lnglat.getLng();
              this.form.latitude = e.lnglat.getLat();
              this.$message.success(`已选择位置：${this.form.longitude}, ${this.form.latitude}`);
            });
          };

          // 尝试获取用户当前位置
          if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
              (position) => {
                const userLocation = [position.coords.longitude, position.coords.latitude];
                initMap(userLocation); // 使用用户的当前位置初始化地图
              },
              (error) => {
                console.warn('获取用户位置失败:', error.message);
                initMap(); // 如果无法获取用户位置，则使用默认的北京位置作为备用
              }
            );
          } else {
            console.warn('浏览器不支持地理定位');
            initMap(); // 如果不支持地理定位，则使用默认的北京位置作为备用
          }

          // 如果PlaceSearch实例未准备好，添加一个短暂的延迟重试
          const checkPlaceSearchReady = () => {
            if (!this.placeSearch && this.isMapReady === false) {
              setTimeout(checkPlaceSearchReady, 500); // 延迟500毫秒后重试
            }
          };
          checkPlaceSearchReady();
        }
      });
    },

    querySearchAsync(queryString, cb) {
      if (queryString) {
        if(this.placeSearch && this.isMapReady){
          this.placeSearch.search(queryString, (status, result) => {
            if (status === 'complete' && result.poiList.count > 0) {
              cb(result.poiList.pois.map(poi => ({
                value: poi.name,
                location: poi.location
              })));
            } else {
              cb([]);
            }
          });
        } else {
          console.error("PlaceSearch instance is not ready.");
          // 可以考虑在此处延迟搜索，直到地图和PlaceSearch准备就绪
          setTimeout(() => {
            this.querySearchAsync(queryString, cb);
          }, 500); // 延迟500毫秒后重试
        }
      } else {
        cb([]);
      }
    },
    handleSelect(item) {
      this.form.longitude = item.location.lng;
      this.form.latitude = item.location.lat;
      this.form.siteAddress = item.value;
      this.map.setCenter([item.location.lng, item.location.lat]);
      this.$message.success(`已选择位置：${item.value} (${item.location.lng}, ${item.location.lat})`);
    },
    submitForm() {
      this.$refs['addSiteForm'].validate((valid) => {
        if (valid) {
          this.$http.post('/merchant/site/add', this.form).then(response => {
            this.$message.success('新增站点成功');
          }).catch(error => {
            console.error('Error:', error);
            this.$message.error('新增站点失败');
          });
        } else {
          console.log('验证失败');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.add-site-container {
  padding: 20px;
}
</style>